'use strict';
const jwt = require('jwt-simple');
const db = uniCloud.database();
exports.main = async (event, context) => {
	// 获取token
	const token = event.token
	// 解码token,得到payload
	const userFromToken = JSON.parse(Buffer.from(token.split('.')[1], 'base64').toString())
	/* 查询openId当前用户 */
	const userInDB = await db.collection('users').where({openId: userFromToken}).get()
	if(userInDB.data.length !== 1) {
		return {
			status: -1,
			errCode: 'TOKEN_INVALID',
			msg: '查无此人'
		}
	}
	
	// 提取用户数据
	const userInfoDB = userInDB.data[0]
	// 对token解码
	let userInfoDecode = jwt.decode(token, userInfoDB.tokenSecret)
	// 如果验证token,并且没有超出exp设置的token有效期
	if(userInfoDB.exp > Date.now() && userInfoDecode == userFromToken) {
		return {
			status: 0,
			openId: userInfoDecode,
			msg: 'token验证成功'
		}
	}
	// 如果验证有效期失败
	if(userInfoDB.exp < Date.now()) {
		return {
			status: -3,
			errCode: 'TOKEN_EXPIRED',
			msg: 'token已失效'
		}
	} 
};
